from django.db import models
from django.contrib.auth.models import User
import re
from collections import Counter
import jieba  # 需要安装: pip install jieba

from django_ckeditor_5.fields import CKEditor5Field


class Column(models.Model):
    name = models.CharField(max_length=100, verbose_name='栏目名称')
    slug = models.SlugField(max_length=100, unique=True, verbose_name='栏目slug')
    description = models.TextField(blank=True, null=True, verbose_name='栏目描述')
    order = models.IntegerField(default=0, verbose_name='排序')

  

    class Meta:
        verbose_name = '栏目'
        verbose_name_plural = '栏目'
        ordering = ['order']

    def __str__(self):
        return self.name

#新增专题模型
class Topic(models.Model):
    name = models.CharField(max_length=50, verbose_name='专题名称')
    slug = models.SlugField(unique=True, verbose_name='URL标识')
    description = models.TextField(blank=True, verbose_name='专题描述')
    cover_image = models.ImageField(upload_to='topics/covers/', blank=True, verbose_name='专题封面')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    def __str__(self):
        return self.name
    
    class Meta:
        verbose_name = '专题'
        verbose_name_plural = '专题管理'
        ordering = ['-created_at']

class Article(models.Model):
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('published', '已发布'),
        ('archived', '归档'),
    ]

    # 基础字段
    id = models.AutoField(primary_key=True, verbose_name='ID')
    title = models.CharField(max_length=200, verbose_name='标题')
    column = models.ForeignKey('Column', on_delete=models.CASCADE, verbose_name='栏目')
    topics = models.ForeignKey('Topic', on_delete=models.SET_NULL, blank=True, null=True, verbose_name='专题')

    redirect_url = models.URLField(blank=True, verbose_name='跳转URL')
    is_recommended = models.BooleanField(default=False, verbose_name='推荐')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='published', verbose_name='状态')
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='作者')
    publish_date = models.DateTimeField(auto_now_add=True, verbose_name='发布日期')
    update_date = models.DateTimeField(auto_now=True, verbose_name='更改日期')
    keywords = models.CharField(max_length=100, blank=True, verbose_name='关键词')

    # 媒体与内容字段
    cover_image = models.ImageField(upload_to='articles/covers/', blank=True, verbose_name='标题图片')
    content = CKEditor5Field(config_name='default')  # 使用对应配置

    def __str__(self):
        return self.title

    def extract_keywords(self):
        # 停用词列表
        stop_words = set(['的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这'])
        
        # 提取标题和内容文本
        text = self.title + ' ' + re.sub(r'<[^>]+>', '', str(self.content))  # 移除HTML标签
        
        # 使用jieba分词
        words = jieba.cut(text)
        
        # 过滤停用词和非中文字符
        filtered_words = [word for word in words if word.strip() and word not in stop_words and re.match(r'^[\u4e00-\u9fa5]+$', word)]
        
        # 统计词频
        word_counts = Counter(filtered_words)
        
        # 获取前5个高频词
        top_words = [item[0] for item in word_counts.most_common(5)]
        
        return ','.join(top_words)

    def save(self, *args, **kwargs):
        # 如果没有手动设置关键词，则自动提取
        if not self.keywords:
            self.keywords = self.extract_keywords()
        super().save(*args, **kwargs)

    class Meta:
        verbose_name = '文章'
        verbose_name_plural = '文章管理'
        ordering = ['-publish_date']
        indexes = [
            models.Index(fields=['status']),
            models.Index(fields=['is_recommended']),
            models.Index(fields=['publish_date']),
            models.Index(fields=['column']),
        ]
